<?php

/**
 * 公用函数
 *
 * 框架所用常用函数
 *
 * @author Lan <lanyg.com@gmail.com>
 * @link http://www.lanyg.com/projects/lanp
 * @copyright Copyright &copy; 2011-2012 Yanguang Lan (www.lanyg.com)
 * @license LGPL (http://www.gnu.org/licenses/lgpl.html)
 * @version $Id$
 */

/**
 * get_domain 获得域名
 */
 function get_domain()
{
    /* 协议 */
    $protocol = (isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://';

    /* 域名或IP地址 */
    if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])){
        $host = $_SERVER['HTTP_X_FORWARDED_HOST'];
    }elseif (isset($_SERVER['HTTP_HOST'])){
        $host = $_SERVER['HTTP_HOST'];
    }else{
        /* 端口 */
        if (isset($_SERVER['SERVER_PORT'])){
            $port = ':' . $_SERVER['SERVER_PORT'];

            if ((':80' == $port && 'http://' == $protocol) || (':443' == $port && 'https://' == $protocol)){
                $port = '';
            }
        }else{
            $port = '';
        }

        if (isset($_SERVER['SERVER_NAME'])){
            $host = $_SERVER['SERVER_NAME'] . $port;
        }elseif (isset($_SERVER['SERVER_ADDR'])){
            $host = $_SERVER['SERVER_ADDR'] . $port;
        }
    }

    return $protocol . $host;
}

/**
 * make_url 封装url
 * @param   string   $str    控制器名/方法名
 * @param   array	 $array  键/值对			
 */
function make_url($str, $array = array())
{
	//make_url('default/index', array('uid'=>'4')) => http://www.example.com/index.php?app=default&act=index&uid=4
	//make_url('default/index', array('uid'=>'4')) => http://www.example.com/index.php/default/index/uid/4
	$config = MVC::instance()->config;
	$domain = ($config['route'] == 2) ? get_domain() . str_replace('/index.php', '', $_SERVER['SCRIPT_NAME']) : get_domain() . $_SERVER['SCRIPT_NAME'];
	
	if(!$config['route']){
		$tmp = explode('/', $str);
		$url = $domain . '?c=' . $tmp[0] . '&a=' . $tmp[1];
		foreach($array as $key=>$value)
		{
			$url .= '&' . $key . '=' .$value; 
		}
	}else{
		$url = $domain . '/' . $str . '/';
		$tmp = array();
		foreach($array as $key=>$value)
		{
			$tmp[] = $key . '/' .$value; 
		}
		$url .= implode('/', $tmp);
		
		if( !empty ($config['routing']['rsearch']) && !empty ($config['routing']['rreplace']) ){
			$url = preg_replace($config['routing']['rsearch'], $config['routing']['rreplace'],$url);
		}
	}
	return $url;
}
?>